package cn.laike.modules.dev.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.laike.common.validator.ValidatorUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import cn.laike.modules.dev.entity.ConfigEntity;
import cn.laike.modules.dev.entity.EarnestMoneyOrderEntity;
import cn.laike.modules.dev.entity.HotelEntity;
import cn.laike.modules.dev.entity.HotelRoomEntity;
import cn.laike.modules.dev.entity.OrderEntity;
import cn.laike.modules.dev.entity.PrinterEntity;
import cn.laike.modules.dev.service.EarnestMoneyOrderService;
import cn.laike.modules.dev.service.HotelRoomBannerService;
import cn.laike.modules.dev.service.HotelRoomService;
import cn.laike.modules.dev.service.HotelService;
import cn.laike.modules.dev.service.PrinterService;
import cn.laike.modules.dev.utils.DevCacheUtils;
import cn.laike.modules.dev.utils.PrinterUtils;
import cn.laike.modules.sys.entity.SysUserEntity;
import cn.laike.modules.sys.shiro.ShiroUtils;
import cn.laike.common.utils.DateUtils;
import cn.laike.common.utils.PageUtils;
import cn.laike.common.utils.R;
import cn.laike.common.utils.XMLUtils;
import cn.laike.common.utils.wxpay.MoneyUtils;



/**
 * 押金记录
 *
 * @author ziye
 * @email 524748907@qq.com
 * @date 2019-03-02 11:23:33
 */
@RestController
@RequestMapping("dev/earnestmoneyorder")
public class EarnestMoneyOrderController {
    @Autowired
    private EarnestMoneyOrderService earnestMoneyOrderService;
    
    @Autowired
    private HotelService hotelService;
    
	@Autowired
    private HotelRoomService hotelRoomService;
	
	@Autowired
    private PrinterService printerService;
	

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("dev:earnestmoneyorder:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = earnestMoneyOrderService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("dev:earnestmoneyorder:info")
    public R info(@PathVariable("id") Integer id){
        EarnestMoneyOrderEntity earnestMoneyOrder = earnestMoneyOrderService.selectById(id);

        return R.ok().put("earnestMoneyOrder", earnestMoneyOrder);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("dev:earnestmoneyorder:save")
    public R save(@RequestBody EarnestMoneyOrderEntity earnestMoneyOrder){
        earnestMoneyOrderService.insert(earnestMoneyOrder);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("dev:earnestmoneyorder:update")
    public R update(@RequestBody EarnestMoneyOrderEntity earnestMoneyOrder){
        ValidatorUtils.validateEntity(earnestMoneyOrder);
        HotelEntity hotel = hotelService.selectById(earnestMoneyOrder.getHotelId());
        if(hotel != null) {
        	earnestMoneyOrder.setHotelName(hotel.getName());
        }else {
        	return R.error("请选择所属酒店");
        }
        HotelRoomEntity hotelRoom = hotelRoomService.selectById(earnestMoneyOrder.getHotelRoomId());
        if(hotelRoom != null) {
        	earnestMoneyOrder.setHotelRoomName(hotelRoom.getName());
        }else {
        	return R.error("请选择所房型");
        }
        earnestMoneyOrderService.updateAllColumnById(earnestMoneyOrder);//全部更新
        
        return R.ok();
    }
    
    @RequestMapping("/updateHotelRoom")
    public R updateHotelRoom(@RequestParam Long id,@RequestParam String hotelRoomName){
    	EarnestMoneyOrderEntity earnestMoneyOrder = earnestMoneyOrderService.selectById(id);
    	earnestMoneyOrder.setHotelRoomName(hotelRoomName);
    	SysUserEntity user = ShiroUtils.getUserEntity();
    	if(user.getHotelId() != null && user.getHotelId() >0 && user.getUserId() == user.getUserId()) {
    		earnestMoneyOrderService.updateAllColumnById(earnestMoneyOrder);//全部更新
    		return R.ok();
    	}else {
    		return R.error("你无权设置");
    	}
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("dev:earnestmoneyorder:delete")
    public R delete(@RequestBody Integer[] ids){
        earnestMoneyOrderService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }
    
    /**
     * 退款
     * @param ids
     * @return
     */
    @RequestMapping("/refundMoney")
    public R refundMoney(Integer id,Double price){
    	
    	EarnestMoneyOrderEntity order = earnestMoneyOrderService.selectById(id);
    	try {
    		if(order != null && order.getRefundFee() >= order.getPrice()){
				return R.error("该订单已退款！");
			}else if(order != null && order.getStatus() != 0){	
				ConfigEntity config = DevCacheUtils.getConfig(order.getUid());
 		 		// 微信支付jsapi 生成json
				/*
				 * String nonceStr = CommonUtil.CreateNoncestr(); WxPayHelper wxPayHelper = new
				 * WxPayHelper(); wxPayHelper.setAppId(config.getAppId());
				 * wxPayHelper.setMchId(config.getMchId());
				 * wxPayHelper.setApiKey(config.getApiKey());
				 */
				String totalFee = String.format("%.0f",order.getPrice()*100);
				String refundFee = String.format("%.0f",price*100);
				Map<String, String> xmlMap = applyRefund(config, order.getOrderNo(), order.getTradeNo(), "", totalFee, refundFee);
				if ("SUCCESS".equals(xmlMap.get("xml.return_code"))) {
					if ("SUCCESS".equals(xmlMap.get("xml.result_code"))) {
						order.setStatus(2);
						if(order.getRefundFee() == null) {
							order.setRefundFee(0d);
						}
						order.setRefundFee(order.getRefundFee() + price);
						order.setRefundTime(new Date()); 
						earnestMoneyOrderService.insertOrUpdate(order);
						
						List<PrinterEntity> printerList = printerService.queryPrinterList(order.getHotelId());
	 	 	 				
 	 	 				for (PrinterEntity printer : printerList) {
 	 	 					PrinterUtils.yajintuikuan(printer.getSn(), order);
 	 	 					PrinterUtils.yajintuikuan(printer.getSn(), order);
 	 	 				}
						return R.ok("退款成功");
					}else{
						return R.error(xmlMap.get("xml.err_code_des"));
					}
				} else {
					return R.error(xmlMap.get("xml.return_msg"));
				}
			}else{
				return R.error("该订单不存在！");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return R.error("请配置商户信息");
		}
		
    }
    
    
    public Map<String,String> applyRefund(ConfigEntity config, String refundNo, String transactionId, String outTradeNo, String totalFee, String refundFee){
		String postUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";//微信退款
		String appKey = config.getApiKey();
		String certFile = config.getCertFile();
		String mchId = config.getMchId();
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("appid", config.getAppId());			//公众账号ID
		map.put("mch_id", config.getMchId());				//商户号
		
		map.put("nonce_str", MoneyUtils.buildRandom());
		map.put("op_user_id", config.getMchId());    //操作员帐号, 默认为商户号
		
		if(StringUtils.isNotBlank(transactionId)){
			map.put("transaction_id", transactionId);		//微信订单号
		}else{
			map.put("out_trade_no", outTradeNo);			//商户订单号
		}
		
		map.put("out_refund_no",refundNo);				//商户退款单号
		map.put("total_fee", totalFee);					//总金额
		map.put("refund_fee", refundFee);				//退款金额
		map.put("sign", MoneyUtils.createSign(map,appKey));
		
		Map<String,String> params =  new HashMap<String, String>();
		try {
			System.out.println(MoneyUtils.createXML(map));
			String result = MoneyUtils.doSendMoney(postUrl, MoneyUtils.createXML(map),mchId,certFile);
			System.out.println("result:"+result);
			Map<String,String> mapTwo = XMLUtils.xml2Map(result);
			return mapTwo;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

    
    /**
     * 统计
     * @param params
     * @return
     */
    @RequestMapping("/statTotalMoney")
    public R getmoneylist(@RequestParam Map<String, Object> params){
    	String startTime = (String)params.get("startTime");
    	String endTime = (String)params.get("endTime");
    	if(StringUtils.isEmpty(startTime)){
    		startTime = DateUtils.format(new Date());
    		params.put("startTime", startTime);
    	}
    	if(StringUtils.isEmpty(endTime)){
    		endTime = DateUtils.format(new Date());
    		params.put("endTime", endTime);
    	}
    	
        List<Double> moneylist = earnestMoneyOrderService.statTotalMoney(ShiroUtils.getUserId(),ShiroUtils.getHotelId(), startTime, endTime); //donationOrderService.statOrderMoney(ShiroUtils.getUserId(), startTime, endTime);
        return R.ok().put("moneylist", moneylist).put("startTime", startTime).put("endTime", endTime);
    }
}
